package com.hongshan.wallet.core.login

import android.app.Application
import android.databinding.ObservableField
import android.view.View
import com.hongshan.wallet.Constant
import com.hongshan.wallet.MyApplication
import com.hongshan.wallet.base.BaseOnPropertyChangedCallback
import com.hongshan.wallet.base.MyViewModel
import com.hongshan.wallet.http.HttpClient
import com.hongshan.wallet.router.RouterIndex
import com.hongshan.wallet.router.go
import com.hongshan.wallet.toast
import com.hongshan.wallet.tryRun
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

/**
 * Copyright Qiandai Ltd.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.core.register
 * @author   : Administrator
 * @data     : 2019/3/18
 * @email    : zhangxx@baihang-china.com
 */
class LoginViewModel(application: Application) : MyViewModel(application) {

    var tel: ObservableField<String> = ObservableField()
    var securityCode: ObservableField<String> = ObservableField()
    var sendTime: ObservableField<String> = ObservableField("发送验证码")
    var pwd: ObservableField<String> = ObservableField("")
    var sendStatus: ObservableField<Boolean> = ObservableField()
    var pwdStateStr = ObservableField("密码登录")
    var pwdState: ObservableField<Boolean> = ObservableField(false)

    val login = View.OnClickListener {
        val telStr = tel.get()?.trim()
        val codeStr = securityCode.get()?.trim()
        val json = Constant.gson.toJsonTree(mapOf("phone_num" to telStr, "code" to codeStr))
        GlobalScope.launch(Dispatchers.Main) {
            showLoading.call()
            val result = GlobalScope.async(Dispatchers.IO) {
                tryRun { HttpClient.httpApi.login(json).execute() }
            }
            val response = result.await() ?: return@launch
            showSuccess.call()
            if (response.isSuccessful) {
                if (response.body()?.code == 0) {
                    MyApplication.user = response.body()?.data
                    MyApplication.user?.save()
                    this@LoginViewModel.finish.call()
                    go(RouterIndex.MAIN)
                } else {
                    toast(response.body()?.msg)
                }
            }
        }
    }

    val send = View.OnClickListener {
        GlobalScope.launch(Dispatchers.Main) {
            val telStr = tel.get()?.trim()
            if (telStr.isNullOrEmpty()) {
                toast("手机号码为空")
                return@launch
            }
            if (!telStr.matches(Constant.Regex.TEL.toRegex())) {
                toast("手机号码不合法")
                return@launch
            }
            sendStatus.set (false)
            val result = GlobalScope.async(Dispatchers.IO) {
                tryRun { HttpClient.httpApi.sendSms(telStr).execute() }
            }
            val body = result.await()?.body()
            if (body?.code == 0) {
                toast("发送成功")
                for (num in 60 downTo 1) {
                    sendTime.set("${num}s")
                    delay(1000)
                }
                sendTime.set("发送验证码")
                sendStatus.set(true)
            } else {
                sendStatus.set(true)
                toast(body?.msg)
            }
        }
    }

    val register = View.OnClickListener {
        go(RouterIndex.REGISTER)
    }

    val switchLoginType = View.OnClickListener {
        pwdState.set(pwdState.get()?.not())
    }

    override fun initial() {
        super.initial()
        pwdState.addOnPropertyChangedCallback(BaseOnPropertyChangedCallback<ObservableField<Boolean>>{ sender,_ ->
            val result = sender.get() == true
            if (result){
                pwdStateStr.set("密码登录")
            } else{
                pwdStateStr.set("验证码登录")
            }
        })
    }

}